<template>
  <div>
    <el-container>
      <el-main>
        <el-col :xs="24">
          <el-card header="导出采购计划表文档">
            <el-button type="primary" @click="setExport2Excel">导 出 文 档</el-button>
          </el-card>
        </el-col>
        <el-col :xs="24">
          <el-card>
            <!--后端完成后 最后添加v-loading="loading" -->
            <el-table :key="itemKey" id='deriveFileTable' ref="multipleTable" :data="tableData" :fit="true" :show-header="true" v-loading="loading">
              <el-table-column :label="'设备检测中心 ' + month + ' 月份物资采购计划表'">
                <!--<el-table-column type="selection"></el-table-column>-->
                <el-table-column prop="id" label="id" sortable="true" v-if="false"></el-table-column>
                <el-table-column prop="materialName" label="物料名称"></el-table-column>
                <el-table-column prop="specification" label="型号及规格"></el-table-column>
                <el-table-column prop="unit" label="单位" width="120px"></el-table-column>
                <el-table-column prop="purchaseNum" label="采购数量" width="200px"></el-table-column>
                <el-table-column prop="partUsed" label="使用部位"></el-table-column>
                <el-table-column prop="remark" label="备注"></el-table-column>
                <!-- 暂时去掉删除功能 及 状态列
                <el-table-column prop="purchaseStatus" label="状态"></el-table-column>
                <el-table-column fixed="right" width="150px">
                  <template slot-scope="scope">
                    <el-button mc-type="column-el-button" size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删 除</el-button>
                  </template>
                </el-table-column>-->
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-main>
    </el-container>
  </div>
</template>

<script>

import { getToken } from '@/utils/auth'
// import FileSaver from 'file-saver'
import XLSX2 from 'xlsx'
import XLSX from 'xlsx-style'
import { deleteById } from '@/api/material-purchase/purchase-plan'
import { initTable } from '@/api/material-purchase/derive-file'

export default {
  data() {
    return {
      tableData: [],
      loading: true,
      month: '', // 记录当前月份
      currentMonth: '', // 发送request请求的参数
      itemKey: '', //  使用key属性强制替换元素，从而触发组件的生命周期钩子或者触发过渡
      todayTimeString: '',
      headers: {
        Authorization: getToken()
      }
    }
  },
  //  在模板渲染成html或者模板编译进路由前调用 created.即：通常初始化某些属性值，然后再渲染成视图
  created() {
    this.init()
    const newDate = new Date()
    this.month = newDate.getMonth() + 1
    this.todayTimeString = newDate.getFullYear() + ' 年 ' + this.month + ' 月 '
  },
  methods: {
    //  初始化界面
    init() {
      const newDate = new Date()
      this.month = newDate.getMonth() + 1
      if (this.month < 10) {
        this.currentMonth = newDate.getFullYear() + '-0' + this.month
      } else {
        this.currentMonth = newDate.getFullYear() + '-' + this.month
      }
      initTable(this.currentMonth).then((response) => {
        // 将按照部门分类的数据 添加至 tableData中，并根据每个部门的数据 进行分类，动态添加一个部门名

        for (var i = 0; i < response.data.length; i++) {
          // 按照部门分类并将 部门名称加入到table 表中 独占一行
          this.tableData.push({ purchaseNum: response.data[i].departmentName })
          for (var j = 0; j < response.data[i].total; j++) {
            this.tableData.push(response.data[i].materialBase[j])
          }
        }
        this.pageTotal = response.data.total
        this.loading = false
        this.itemKey = Math.random()
      })
    },
    setExport2Excel() {
      /* generate workbook object from table */
      var xlsxParam = { raw: true }
      var wb = XLSX2.utils.table_to_sheet(document.querySelector('#deriveFileTable'), xlsxParam) //  括号内为表格的id名
      if (!wb['!merges']) {
        this.$message.warning('无法导出：报表无数据')
        return
      }
      for (var i = 0; i < 10; i++) { // 构建 A - F 列的数据
        wb['!cols'][i] = { wpx: 200 }
      }
      // 样式的文档地址
      // https://www.npmjs.com/package/xlsx-style
      for (const key in wb) {
        // console.log('key: ' + key)
        // console.log('wb[key]: ' + wb[key])
        // console.log('wb[key].v: ' + wb[key].v)
        if (key.indexOf('!') === -1 && wb[key].v) {
          if (key === 'A1') {
            console.log('key.indexOf():' + key.indexOf('A'))
            wb[key].s = {
              font: { //  字体设置
                sz: 25,
                bold: false,
                color: {
                  rgb: '000000' //  十六进制，不带#
                }
              },
              alignment: { //  文字居中
                horizontal: 'center',
                vertical: 'center',
                wrap_text: true
              },
              border: { // 设置边框
                top: { style: 'thin' },
                bottom: { style: 'thin' },
                left: { style: 'thin' },
                right: { style: 'thin' }
              }
            }
          } else {
            wb[key].s = {
              font: { //  字体设置
                sz: 18,
                bold: false,
                color: {
                  rgb: '000000' //  十六进制，不带#
                }
              },
              alignment: { //  文字居中
                horizontal: 'center',
                vertical: 'center',
                wrap_text: true
              },
              border: { // 设置边框
                top: { style: 'thin' },
                bottom: { style: 'thin' },
                left: { style: 'thin' },
                right: { style: 'thin' }
              }
            }
          }
        }
      }
      var data = this.addRangeBorder(wb['!merges'], wb) //  合并项添加边框
      var filedata = this.sheet2blob(data)
      this.openDownloadDialog(filedata, this.todayTimeString + '-物资采购计划表.xlsx')
    },
    //  为合并项添加边框
    addRangeBorder(range, ws) {
      const arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
        'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

      range.forEach(item => {
        // eslint-disable-next-line prefer-const
        let startColNumber = Number(item.s.r); let endColNumber = Number(item.e.r)
        const startRowNumber = Number(item.s.c); const endRowNumber = Number(item.e.c)
        const test = ws[arr[startRowNumber] + (startColNumber + 1)]
        for (let col = startColNumber; col <= endColNumber; col++) {
          for (let row = startRowNumber; row <= endRowNumber; row++) {
            ws[arr[row] + (col + 1)] = test
          }
        }
      })
      return ws
    },
    //  将一个sheet转成最终的excel文件的blob对象，然后利用URL.createObjectURL下载
    sheet2blob(sheet, sheetName) {
      sheetName = sheetName || 'sheet1'
      var workbook = {
        SheetNames: [sheetName],
        Sheets: {}
      }
      workbook.Sheets[sheetName] = sheet // 生成excel的配置项

      var wopts = {
        bookType: 'xlsx', // 要生成的文件类型
        bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
        type: 'binary'
      }
      var wbout = XLSX.write(workbook, wopts)
      var blob = new Blob([s2ab(wbout)], {
        type: 'application/octet-stream'
      }) // 字符串转ArrayBuffer
      function s2ab(s) {
        var buf = new ArrayBuffer(s.length)
        var view = new Uint8Array(buf)
        for (var i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF
        return buf
      }
      return blob
    },
    openDownloadDialog(url, saveName) {
      if (typeof url === 'object' && url instanceof Blob) {
        url = URL.createObjectURL(url) // 创建blob地址
      }
      var aLink = document.createElement('a')
      aLink.href = url
      aLink.download = saveName || '' // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
      var event
      if (window.MouseEvent) event = new MouseEvent('click')
      else {
        event = document.createEvent('MouseEvents')
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
      }
      aLink.dispatchEvent(event)
    },
    //  根据 id 删除物料
    handleDelete(index, row) {
      this.$confirm('此操作将删除物料信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteById(this.tableData[index].id).then((response) => {
          this.$message.success(response.message)
          this.loading = true
          this.init()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style scoped>
</style>
